package com.ljkj.cordial.chat.presenter.response;

import android.app.Activity;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.lanjiu.lib.imclient.bus.EventConstants;
import com.lanjiu.lib.imclient.bus.MessageEvent;
import com.lanjiu.lib.imclient.dto.extra.UserChatTable;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.ims.IMSUtils;
import com.lanjiu.pro.business.BusinessProtocolEntities;
import com.lanjiu.pro.business.BusinessProtocolMessages;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.EmptyMessageEvent;
import com.ljkj.cordial.chat.bean.MsgType;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.dao.notify.BusinessLeaveTable;
import com.ljkj.cordial.chat.dao.notify.ChatContentTable;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.notify.NotificationHelper;
import com.ljkj.cordial.chat.notify.NotificationUtils;
import com.ljkj.cordial.chat.ui.ChatUtils;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.ljkj.cordial.chat.util.SpeechVoiceUtil;
import com.nic.view.util.JLog;

import org.greenrobot.eventbus.EventBus;

public class FriendChatProtocolResponse extends AResponseBusinessPresenter {
    private Activity activity;
    private boolean isOnScreen = true;

    @Override
    public void onResponse(Activity activity, boolean isOnScreen, String msgType, Object msg) {
        this.activity = activity;
//        PromptTone.ring(activity);
        this.isOnScreen = isOnScreen;
        BusinessProtocolMessages.FriendChatProtocol response = (BusinessProtocolMessages.FriendChatProtocol) msg;
        BusinessProtocolEntities.ChatMessage chatMessage = response.getChatMessage();
        BusinessProtocolEntities.TouristsUser touristsUser = response.getTouristsUser();
        BusinessProtocolEntities.RegisteredUser registeredUser = response.getRegisteredUser();
        BusinessProtocolEntities.TouristsFriend tourisFriend = response.getTouristsFriend();
        BusinessProtocolEntities.RegisteredFriend regFriend = response.getRegisteredFriend();
        FriendTable friendTable = null;
        if (response.hasTouristsUser() && !ChatApp.getInstance().getUserId().equals(touristsUser.getTemporaryId())) {
            friendTable = setFriendTable(friendTable, IMSContacts.UserType.TOURISTS_USER, touristsUser.getTemporaryId(), touristsUser.getAvatar(), touristsUser.getNickname());
        }
        if (response.hasRegisteredUser() && !ChatApp.getInstance().getUserId().equals(registeredUser.getUserId())) {
            friendTable = setFriendTable(friendTable, IMSContacts.UserType.REGISTERED_USER, registeredUser.getUserId(), registeredUser.getAvatar(), registeredUser.getNickname());
        }
        if (response.hasRegisteredFriend()) {
            if (!ChatApp.getInstance().getUserId().equals(regFriend.getFriendUserId())) {
                friendTable = setFriendTable(friendTable, regFriend.getUserType(), regFriend.getFriendUserId(), regFriend.getFriendAvatar(), regFriend.getFriendNickname());
            }
            if (regFriend.hasSettings()) {
                BusinessProtocolEntities.Settings set = regFriend.getSettings();
                friendTable.setSnapchatStatus(set.getSnapchatStatus());
                friendTable.setSnapchatTimeLength(set.getSnapchatTimeLength());
                friendTable.setOnlineStatus(set.getOnlineStatus() ? Canstants.ONLINE : Canstants.OFFLINE);
            }

        }

        if (response.hasTouristsFriend()) {
            if (!ChatApp.getInstance().getUserId().equals(tourisFriend.getFriendUserId())) {
                friendTable = setFriendTable(friendTable, tourisFriend.getUserType(), tourisFriend.getFriendUserId(), tourisFriend.getFriendAvatar(), tourisFriend.getFriendNickname());
            }
            if (tourisFriend.hasSettings()) {
                BusinessProtocolEntities.Settings set = tourisFriend.getSettings();
                friendTable.setSnapchatStatus(set.getSnapchatStatus());
                friendTable.setSnapchatTimeLength(set.getSnapchatTimeLength());
                friendTable.setOnlineStatus(set.getOnlineStatus() ? Canstants.ONLINE : Canstants.OFFLINE);
            }
        }

        if (response.hasChatMessage() && !TextUtils.isEmpty(friendTable.getFriendUserId())) {

            ChatTableBean chatTableBean = new ChatTableBean();
            chatTableBean.setChatName(friendTable.getFriendUserId());
            chatTableBean.setFromType(Canstants.SINGLE_CHAT);
            chatTableBean.setMsgId(chatMessage.getMsgId());
            chatTableBean.setTargetId(friendTable.getFriendUserId());
            chatTableBean.setTargetName(TextUtils.isEmpty(friendTable.getFriendAlias()) ? friendTable.getFriendNickname() : friendTable.getFriendAlias());
            chatTableBean.setTargetType(friendTable.getUserType());
            chatTableBean.setSendType(ChatTableBean.RECEIVE);
            chatTableBean.setChatUnRead(ChatTableBean.UNREAD);
            chatTableBean.setSendState(ChatTableBean.SEND_SUCCESS);
            chatTableBean.setChatAvatarUrl(friendTable.getFriendAvatar());
            chatTableBean.setReadFinishTime(friendTable.getSnapchatTimeLength());
            chatTableBean.setStartReadFinish(friendTable.getSnapchatStatus());
            chatTableBean.setMsgTime(System.currentTimeMillis());
            chatTableBean.setHistoryTime(ChatUtils.analysisTimestampInMessageId(chatMessage.getMsgId()));
            if (chatMessage.hasFile()) {
                BusinessProtocolEntities.File file = chatMessage.getFile();
                String url = file.getUrl();
                chatTableBean.setFileUrl(url);
                chatTableBean.setFileLength(file.getLength());
                chatTableBean.setChatType(MsgType.ANNEX);
                insert(friendTable, chatTableBean);
            } else if (chatMessage.hasPicture()) {
                BusinessProtocolEntities.Picture pic = chatMessage.getPicture();
                chatTableBean.setFileUrl(pic.getUrl());
                chatTableBean.setChatType(MsgType.Picture);
                chatTableBean.setThumbPath(AlbumManageUtil.getImagePathByByteString(pic.getThumbnail()));
                insert(friendTable, chatTableBean);
            } else if (chatMessage.hasText()) {
                BusinessProtocolEntities.Text txt = chatMessage.getText();
                chatTableBean.setChatType(MsgType.Text);
                if (chatMessage.getChatType() > 4) {//留言
                    JLog.d("insert leave msg");
                    BusinessLeaveTable table = new BusinessLeaveTable();
                    table.setTargetLeave(txt.getContent());
                    table.setTargetUserId(friendTable.getFriendUserId());
                    table.setTargetUserName(friendTable.getFriendNickname());
                    table.setTargetUserType(friendTable.getUserType());
                    table.setTargetStatus(chatMessage.getChatType());
                    table.setAvatarUrl(friendTable.getFriendAvatar());
                    table.setMsgId(chatMessage.getMsgId());
                    BusinessLeaveTable.insert(table, BusinessLeaveTable.FRIEND_LEAVE);
                    if (isOnScreen) {
                        refresh(activity);
                    }
                    if (chatMessage.getChatType() == IMSContacts.MsgContentType.APPLY_FRIEND_TOURISTS ||
                            chatMessage.getChatType() == IMSContacts.MsgContentType.APPLY_FRIEND_REGISTERED) {
                        NotificationUtils.notifyFriend(activity, friendTable, NotificationHelper.NTYPE_FRIEND_APPLY);
                    } else if (chatMessage.getChatType() == IMSContacts.MsgContentType.APPLY_REFUSE_FRIEND_TOURISTS ||
                            chatMessage.getChatType() == IMSContacts.MsgContentType.APPLY_REFUSE_FRIEND_REGISTERED) {
                        NotificationUtils.notifyFriend(activity, friendTable, NotificationHelper.NTYPE_FRIEND_REFUSE);
                    }
                    return;
                }
                if (!TextUtils.isEmpty(txt.getContent())) {
                    chatTableBean.setTextMsg(txt.getContent());
                    insert(friendTable, chatTableBean);
//                    FriendTable finalFriendTable = friendTable;
//                    EmojiPackage.handlerEmojiText(txt.getContent(), new EmojiPackage.OnSpannableListener() {
//                        @Override
//                        public void deCode(SpannableStringBuilder text) {
//                            chatTableBean.setTextMsg(txt.getContent());
//                            chatTableBean.setCharSequenceText(TextCharSequenceTran.create(text));
//                            insert(finalFriendTable, chatTableBean);
//                        }
//                    });
                }


            } else if (chatMessage.hasVoice()) {
                BusinessProtocolEntities.Voice voi = chatMessage.getVoice();
                chatTableBean.setChatType(MsgType.Voice);
                chatTableBean.setThumbPath(SpeechVoiceUtil.analysisPath(voi.getContent()));
                chatTableBean.setChatAvatarId(String.valueOf(SpeechVoiceUtil.analysisDuration(chatTableBean.getThumbPath())));
                insert(friendTable, chatTableBean);
            } else if (chatMessage.hasVideo()) {
                BusinessProtocolEntities.Video vid = chatMessage.getVideo();
                chatTableBean.setChatType(MsgType.Video);
                chatTableBean.setThumbPath(AlbumManageUtil.getImagePathByByteString(vid.getThumbnail()));
                chatTableBean.setFileUrl(vid.getUrl());
                insert(friendTable, chatTableBean);
            }
        }
//        NotificationUtils.messageNotify(activity);
        NotificationUtils.notifyFriend(activity, friendTable, NotificationHelper.NTYPE_FRIEND_CHAT);
    }


    private FriendTable setFriendTable(FriendTable friendTable, String userType, String friendUserId, String friendAvatar, String friendNickname) {
        if (friendTable == null) {
            friendTable = FriendTable.getRowByFriendUserIdNotNull(friendUserId);
        }
        if (!TextUtils.isEmpty(friendUserId)) {
            friendTable.setFriendUserId(friendUserId);
        }
        if (!TextUtils.isEmpty(friendAvatar)) {
            friendTable.setFriendAvatar(friendAvatar);
        }
        if (!TextUtils.isEmpty(friendNickname)) {
            friendTable.setFriendNickname(friendNickname);
        }
        friendTable.setUserType(IMSUtils.userTypeAnalysis(friendUserId));
        return friendTable;
    }


    @Override
    public void insert(Object... table) {
        try {
            FriendTable friendTable = (FriendTable) table[0];
            FriendTable.insert(friendTable);
            ChatTableBean chatTableBean = (ChatTableBean) table[1];
            ChatTableBean.insertWhenMsgIdNotExist(chatTableBean);
            update(friendTable, chatTableBean);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(Object... table) {
        super.update(table);
        FriendTable friendTable = (FriendTable) table[0];
        ChatTableBean chatTable = (ChatTableBean) table[1];
        ChatContentTable chatTableBean = ChatContentTable.queryRowByTargetIdNotNull(friendTable.getFriendUserId(), Canstants.SINGLE_CHAT);
        chatTableBean.setChatType(Canstants.SINGLE_CHAT);
        chatTableBean.setTargetId(friendTable.getFriendUserId());
        chatTableBean.setTargetName(TextUtils.isEmpty(friendTable.getFriendAlias()) ? friendTable.getFriendNickname() : friendTable.getFriendAlias());
        chatTableBean.setTargetType(friendTable.getUserType());
        chatTableBean.setTargetAvatarUrl(friendTable.getFriendAvatar());
//        chatTableBean.setTargetAvatarPath(friendTable.getFriendAvatarPath());
        chatTableBean.setLastMsgType(chatTable.getChatType());
        chatTableBean.setLastMsg(chatTable.getTextMsg());
        chatTableBean.setIsSnapchat(chatTable.getStartReadFinish() ? 1 : 0);
        chatTableBean.setUpdateTime(chatTable.getHistoryTime());
        chatTableBean.setIsRead(0);
        ChatContentTable.insert(chatTableBean);
        JLog.d("->" + friendTable.getFriendAvatar());
//        if (!TextUtils.isEmpty(friendTable.getFriendAvatar())) {
//            if (activity != null && !activity.isFinishing()) {
//                activity.runOnUiThread(() ->
//                        AlbumManageUtil.getInstance().downLoadFileFriendAvatar(friendTable.getFriendAvatar(), friendTable.getFriendUserId(), new AlbumManageUtil.OnFileResponse() {
//                            @Override
//                            public void onResult(String url, String filePath) {
//                                JLog.d(">>>>"+url+"\n"+filePath);
//                                ObserverThread.create().onBackGroudThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        try {
//                                            DaoSession dbSession = DbController.getInstance().getWrite();
//                                            chatTableBean.setTargetAvatarUrl(url);
//                                            chatTableBean.setTargetAvatarPath(filePath);
//                                            dbSession.getChatContentTableDao().update(chatTableBean);
//                                        } catch (Exception e) {
//                                            e.printStackTrace();
//                                        } finally {
//                                            refreshChatData(friendTable, chatTable, chatTable.getMsgTime());
//                                        }
//                                    }
//                                });
//                            }
//                        })
//
//                );
//            }
//        } else {
        refreshChatData(friendTable, chatTable, chatTable.getHistoryTime());
//        }
    }

    private void refreshChatData(FriendTable friendTable, ChatTableBean chatTable, long historyTime) {
        MessageEvent event = MessageEvent.cerateUiRefresh(EventConstants.Action.CHAT_REFRESH);
        UserChatTable uChat = new UserChatTable(chatTable.getTargetId(), chatTable.getTargetName(), Canstants.SINGLE_CHAT, chatTable.isStartReadFinish(), chatTable.getChatType(), chatTable.getTextMsg(), historyTime);
        uChat.setReceiveType(UserChatTable.RECEIVE_FROM_NET);
        event.setData(new Gson().toJson(uChat));
        EventBus.getDefault().post(event);
        postEvent(new EmptyMessageEvent(Canstants.SINGLE_CHAT, friendTable.getFriendUserId(), friendTable.getFriendNickname(), friendTable.getUserType(), chatTable.getMsgId()));
        refresh(activity);
    }
}
